const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const User = mongoose.model('user')
const Group = mongoose.model('group')
const config = require('../config')
const { formatBody } = require('../tools')

module.exports = {
  // 获取分组列表
  async getGroupList (info, socket, cb) {
    let userGroups = await User.findOne({ _id: info._id })
      .populate({
        path: 'groups',
        select: 'avatar nickname _id lastWord lastWordTime',
        populate: {
          path: 'lastWord',
          select: 'content createAt from msgType',
          populate: {
            path: 'from',
            select: 'nickname'
          }
        }
      })
    if (userGroups) {
      let groups = userGroups.groups.map(item => {
        // console.log(`${userGroups.nickname}已经连接群聊>>>${item.nickname}`)
        socket.join(item._id)
        let group = {
          avatar: item.avatar,
          _id: item._id,
          nickname: item.nickname,
          type: 'group'
        }
        if(item.lastWord) {
          group.lastWord = item.lastWord.content
          group.msgType = item.lastWord.msgType
          group.lastWordTime = item.lastWord.createAt
          group.lastWordSender = item.lastWord.from.nickname
        }
        return group
      })
      return cb(formatBody(1, 'ok', groups))
    } else {
      return cb(formatBody(1, '你尚未加入任何分组', []))
    }
  },
  async searchGroup (info, socket, cb) {
    let group = await Group.find({
      $or: [
        {
          nickname: {
            $regex: info.keyword,
            $options: '$i'
          }
        },
        {
          describe: {
            $regex: info.keyword,
            $options: '$i'
          }
        }
      ]
    }).sort({ 'lastUpdate': -1 }).limit(30)
    cb(formatBody(1, 'ok', group))
  },
  async getGroupInfo (info, socket, cb) {
    let group = await Group.findOne({_id: info._id })
    if (group) return cb(formatBody(1, 'ok', group))
    return cb(formatBody(0, '不存在的群聊'))
  },
  async createGroup (info, socket, cb) {
    let { nickname, describe, avatar, creator } = info
    let user = await User.findOne({ _id: creator })
    if (!user) return cb(formatBody(0, '用户不存在'))
    let userGroup = user.groups
    if (userGroup.length >= 7) return cb(formatBody(0, '最多只能加入7个群'))
    let group = new Group({
      nickname, describe, avatar, creator,
      members: [creator]
    })
    await group.save()
    userGroup.push(group._id)
    await User.update({
      _id: creator
    }, {
      groups: userGroup
    })
    return cb(formatBody(1, 'ok', group))
  },
  async joinGroup (info, socket, cb) {
    let { uid, _id } = info
    let user = await User.findOne({ _id: uid })
    let userGroup = user.groups
    if (userGroup.length >= 7) return cb(formatBody(0, '最多只能加入7个群'))
    let group = await Group.findOne({ _id: _id })
    let groupMembers = group.members
    if (groupMembers.indexOf(uid) > -1) return cb(formatBody(0, '您已经在该群聊了'))
    userGroup.push(_id)
    groupMembers.push(uid)
    await User.update({
      _id: uid
    }, {
      groups: userGroup
    })
    await Group.update({
      _id: _id
    }, {
      members: groupMembers
    })
    return cb(formatBody(1, '加入成功'))
  },
  async getGroupMembers (info, socket, cb) {
    let group = await Group.findOne({_id: info._id })
    let promise = group.members.map(async item => {
      const user = await User.findOne({ _id: item })
      let { _id, nickname, sex, place, avatar, lastOnline} = user
      return { _id, nickname, sex, place, avatar, lastOnline }
    })
    Promise.all(promise).then(members => {
      return cb(formatBody(1, 'ok', members))
    })   
  },
  async updateGroupInfo (info, socket, cb) {
    let { nickname, _id, describe, avatar, uid } = info
    let group = await Group.findOne({ _id: _id })
    // console.log(uid, group.creator)
    if (uid != group.creator) {
      return cb(formatBody(0, '只有群主才能修改群信息哦'))
    }
    if (Date.now() - new Date(group.lastUpdate).getTime() < 1000 * 60 * 60 * 24) {
      return cb(formatBody(0, '每24小时只能更改一次群信息'))
    } else {
      await Group.update({
        _id: _id
      }, {
        nickname, describe, avatar,
        lastUpdate: new Date()
      })
      return cb(formatBody(1, 'ok'))
    }
  }
}
